package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.pojo.Question;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.*;
import com.tanhua.dubbo.server.enums.HuanXinMessageType;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.server.vo.NearUserVo;
import com.tanhua.server.vo.TodayBest;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class TanHuaService {
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private QuestionService questionService;

    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    @Value("${tanhua.default.recommend.users}")
    private String defaultRecommendUsers;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;
    @Autowired
    private IMService imService;

    /**
     * 查询个人主页的个人信息
     *
     * @param userId 要查看的那个用户id
     * @return
     */
    public TodayBest queryUserInfo(Long userId) {
        //通过id获取用户信息
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(userId);
        //如果为null, 则直接返回
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }

        // 封住信息展示给用户
        TodayBest todayBest = new TodayBest();
        todayBest.setId(userId);
        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setGender(userInfo.getSex().name().toLowerCase());
        todayBest.setTags(Convert.toStrArray(StrUtil.split(userInfo.getTags(), ',')));
        User user = UserThreadLocal.get();
        todayBest.setFateValue(recommendUserService.queryScore(userId, user.getId()).longValue());
        todayBest.setNickname(userInfo.getNickName());

        //记录来访用户
        visitorsApi.saveVisitor(userId,user.getId(),"个人主页 ");

        return todayBest;
    }

    /**
     * 查询陌生人问题
     *
     * @param userId
     * @return
     */
    public String queryQuestion(Long userId) {
        Question question = questionService.queryQuestion(userId);
        if (ObjectUtil.isNotEmpty(question)) {
            return question.getTxt();
        }
        // 默认问题
        return "你有严重恐高症，女朋友却让你背她走玻璃栈道，你是选择背她上去，还是选择珍惜生命？";
    }

    /**
     * 回复陌生人问题
     * @param userId  陌生人的id
     * @param reply  消息内容
     * @return
     */
    public Boolean replyQuestion(Long userId, String reply) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(user.getId());
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId());
        msg.put("huanXinId", "HX_" + user.getId());
        msg.put("nickname", userInfo.getNickName());
        msg.put("strangerQuestion", queryQuestion(userId));
        msg.put("reply",reply);
        return huanXinApi.sendMsgFromAdmin("HX_" + userId, HuanXinMessageType.TXT , JSONUtil.toJsonStr(msg));
    }

    /**
     * 搜附近
     *
     * @param gender  性别
     * @param distance  距离
     * @return
     */
    public List<NearUserVo> queryNearUser(String gender, String distance) {
        User user = UserThreadLocal.get();
        // 获取用户当前位置信息
        UserLocationVo userLocationVo = userLocationApi.queryByUserId(user.getId());
        if (ObjectUtil.isEmpty(userLocationVo)){
            //返回空集合
            return ListUtil.empty();
        }
        PageInfo<UserLocationVo> pageInfo = userLocationApi.queryUserFromLocation(userLocationVo.getLongitude(), userLocationVo.getLatitude(),
                Convert.toDouble(distance), 1, 50);
        List<UserLocationVo> records = pageInfo.getRecords();
        if (ObjectUtil.isEmpty(records)){
            //返回空集合
            return ListUtil.empty();
        }
        //筛选构造条件
        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id",userIdList);
        if (StrUtil.equalsAnyIgnoreCase(gender,"man")){
            queryWrapper.eq("sex", SexEnum.MAN);
        }else if (StrUtil.equalsAnyIgnoreCase(gender,"woman")){
            queryWrapper.eq("sex", SexEnum.WOMAN);
        }

        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);

        List<NearUserVo> nearUserVoList = new ArrayList<>();
        for (UserLocationVo locationVo : records) {
            // 排除自己
            if (ObjectUtil.equals(locationVo.getUserId(),user.getId())){
                continue;
            }
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(locationVo.getUserId(),userInfo.getUserId())){
                    NearUserVo nearUserVo = new NearUserVo();
                    nearUserVo.setUserId(userInfo.getUserId());
                    nearUserVo.setAvatar(userInfo.getLogo());
                    nearUserVo.setNickname(userInfo.getNickName());
                    nearUserVoList.add(nearUserVo);
                    break;
                }
            }
        }

        return nearUserVoList;
    }

    /**
     * 探花
     * @return
     */
    public List<TodayBest> queryCardsList() {
        User user = UserThreadLocal.get();
        int count = 50;
        List<RecommendUser> recommendUserList = recommendUserService.queryCardList(user.getId(), count);
        if (ObjectUtil.isEmpty(recommendUserList)){
            recommendUserList = new ArrayList<>();
            // 默认推荐列表
            List<String> split = StrUtil.split(defaultRecommendUsers, ',');
            for (String userId : split) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Convert.toLong(userId));
                recommendUser.setToUserId(user.getId());
                recommendUserList.add(recommendUser);

            }
        }

        //计算展现的数量，默认展现10个
        int showCount = Math.min(10, recommendUserList.size());
        List<RecommendUser> result = new ArrayList<>();
        for (int i = 0; i < showCount; i++) {
            int index = RandomUtil.randomInt(0, recommendUserList.size());
            RecommendUser recommendUser = recommendUserList.get(index);
            result.add(recommendUser);
        }

        // 通过推荐用户结果, 获取所用的用户id
        List<Object> userIdList = CollUtil.getFieldValues(result, "userId");
        // 通过用户id查询到所有用户信息
        List<UserInfo> userInfoList = userInfoService.queryUserInfoByUserIdList(userIdList);
        List<TodayBest> todayBestList = new ArrayList<>();
        // 封装需要返回的信息
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setAge(userInfo.getAge());
            todayBest.setTags(Convert.toStrArray(StrUtil.split(userInfo.getTags(),',')));
            todayBest.setFateValue(0L);

            todayBestList.add(todayBest);
        }
        return todayBestList;
    }

    /**
     * 喜欢
     *
     * @param likeUserId
     * @return
     */
    public Boolean likeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        Boolean result = userLikeApi.likeUser(user.getId(), likeUserId);
        if (!result){
            return false;
        }
        if (userLikeApi.isMutualLike(user.getId(), likeUserId)){
            imService.contactUser(likeUserId);
        }
        return true;
    }

    /**
     * 不喜欢
     *
     * @param likeUserId
     * @return
     */
    public Boolean notLikeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        return userLikeApi.notLikeUser(user.getId(), likeUserId);
    }
}
